package me.illtamer.infinite.file.parser;

import lombok.extern.slf4j.Slf4j;
import me.illtamer.infinite.config.Configuration;
import me.illtamer.infinite.file.FileType;
import me.illtamer.infinite.file.source.FileSource;
import me.illtamer.infinite.hook.TranslatorAdaptor;
import me.illtamer.infinite.pojo.Response;
import me.illtamer.infinite.pojo.TransObject;
import me.illtamer.infinite.util.JsonUtil;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class TextParser implements TypeParser {

    @Override
    public void parse(TranslatorAdaptor adaptor, FileSource source) throws IOException {
        String content = source.getContent();

        List<String> requestList = new LinkedList<>();
        List<String> responseList = new LinkedList<>();

        List<List<String>> translateList = new LinkedList<>();

        long size = 0;
        int index = -1, last = 0;
        while ((index = content.indexOf('.', index + 1)) != -1) {
            String part = content.substring(last + 1, index + 1);

            if (size + part.length() > adaptor.getMaxLength()) {
                if (part.length() > adaptor.getMaxLength())
                    throw new IllegalArgumentException("Too long text length ! Limited: " + adaptor.getMaxLength() + " Found: " + part.length());
                translateList.add(requestList);
                requestList = new LinkedList<>();
                requestList.add(part);
                size = part.length();
            } else {
                requestList.add(part);
                size += part.length();
            }

            last = index;
        }
        translateList.add(requestList);

        if (content.length() - last + size <= adaptor.getMaxLength())
            requestList.add(content.substring(last));
        else if (content.length() - last <= adaptor.getMaxLength())
            translateList.add(Collections.singletonList(content.substring(last)));
        else
            throw new IllegalArgumentException("Too long text length ! Limited: " + adaptor.getMaxLength() + " Found: " + (content.length() - last));

        for (List<String> requests : translateList) {
            StringBuilder builder = new StringBuilder();
            for (String request : requests)
                builder.append(request).append("\n");

            // json字符串
            String response = adaptor.translate(builder.toString(), "auto", "zh")
                    .replace("#=", ">").replace("=#", "<");

            TransObject object = JsonUtil.getObject(response);
            if (object.getResponse() != Response.SUCCESS) {
                log.warn("Failed translate {}", object);
                continue;
            }

            List<String> values = object.getTransPairs().stream().map(TransObject.TransPair::getDst).collect(Collectors.toList());
            responseList.addAll(values);
        }

        File targetFile = new File(Configuration.TARGET_FOLDER, source.getName());
        if (!targetFile.createNewFile()) {
            log.warn("Can not create file({}), is it already exists ?", targetFile.getAbsolutePath());
        }

        try (FileWriter writer = new FileWriter(targetFile)) {
            responseList.forEach(response -> {
                try {
                    writer.append(response).append("\r\n");
                } catch (IOException e) {
                    log.error("Error occurred when write a file({})", targetFile);
                }
            });
        }

    }

    @Override
    public FileType parserType() {
        return FileType.TXT;
    }

}
